package com.buddies.lottery.ui.lottery.bet;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.buddies.lottery.R;
import com.buddies.lottery.base.BaseFragment;
import com.buddies.lottery.data.bean.Lottery;
import com.buddies.lottery.data.bean.LotteryBetRecord;
import com.buddies.lottery.data.result.PageResult;
import com.buddies.lottery.ui.lottery.bet.detail.LotteryBetDetailActivity;
import com.buddies.lottery.widget.OnTabClickListener;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LotteryBetRecordFragment extends BaseFragment<LotteryBetRecordContract.Presenter> implements LotteryBetRecordContract.View, OnTabClickListener {

    private SwipeRefreshLayout mSwipeRefreshLayout;

    private RecyclerView mRecyclerView;
    private GridLayoutManager mLayoutManager;
    private LotteryBetRecordAdapter mAdapter;
    private int mPage = 1;
    private int mStatus;

    public static LotteryBetRecordFragment newInstance(int status) {
        Bundle args = new Bundle();
        args.putSerializable("status", status);

        LotteryBetRecordFragment fragment = new LotteryBetRecordFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            mStatus = args.getInt("status");
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_lottery_category;
    }

    @Override
    public void initView() {
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresher);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                forceRefresh();
            }
        });

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    }

    @Override
    public void initData() {
        mPresenter = new LotteryBetRecordPresenter(this);

        mLayoutManager = new GridLayoutManager(getActivity(), 1, GridLayoutManager.VERTICAL, false);

        mAdapter = new LotteryBetRecordAdapter(null);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                LotteryBetDetailActivity.launch(getActivity(), mAdapter.getItem(position));
            }
        });
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                onLoadMore();
            }
        }, mRecyclerView);
        mAdapter.setEmptyView(R.layout.view_empty, mSwipeRefreshLayout);

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onResume() {
        super.onResume();

        forceRefreshIfNeed();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        forceRefreshIfNeed();
    }

    private boolean isUserVisible() {
        LotteryBetRecordActivity activity = (LotteryBetRecordActivity) getActivity();
        return getUserVisibleHint() && activity != null && activity.getCurrentTab() == mStatus;
    }

    private void forceRefreshIfNeed() {
        if (isUserVisible() && mAdapter != null && mAdapter.getItemCount() <= 1) {
            forceRefresh();
        }
    }

    protected void forceRefresh() {
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
                mRecyclerView.smoothScrollToPosition(0);
                mPage = 1;
                onLoadData(mPage);
            }
        });
    }

    protected void onLoadData(int page) {
        int lotteryId = 0;
        LotteryBetRecordActivity activity = (LotteryBetRecordActivity) getActivity();
        if (activity != null) {
            Lottery lottery = activity.getLottery();
            if (lottery != null) {
                lotteryId = lottery.id;
            }
        }

        Map<String, Object> params = new HashMap<>();
        params.put("lotteryId", lotteryId);
        params.put("period", "");
        params.put("status", String.valueOf(mStatus));
        mPresenter.loadLotteryBetRecord(params, page);
    }

    public void onLoadMore() {
        mPage++;
        onLoadData(mPage);
    }

    @Override
    public void onLotteryBetRecordLoaded(PageResult<LotteryBetRecord> response) {
        mSwipeRefreshLayout.setRefreshing(false);

        List<LotteryBetRecord> list = response.list;
        if (response.page <= 1) {
            mAdapter.setNewData(list);
        } else {
            mAdapter.addData(list);
        }
        if (list != null && !list.isEmpty()) {
            mAdapter.loadMoreComplete();
        } else {
            mAdapter.loadMoreEnd();
        }
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onTabClick() {
        if (mLayoutManager != null) {
            int currentPosition = mLayoutManager.findFirstCompletelyVisibleItemPosition();
            if (currentPosition == 0 || mAdapter.getItemCount() == 0) {// 第一页
                forceRefresh();
            } else if (mRecyclerView != null) {
                if (currentPosition > 12) {
                    mRecyclerView.scrollToPosition(12);
                }
                mRecyclerView.smoothScrollToPosition(0);
            }
        }
    }

    public void clearData() {
        mAdapter.setNewData(null);
    }

}
